package net.huashitong.webMsg.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.core.web.model.Ztree;
import com.sirdc.modules.sys.entity.SysFile;
import com.sirdc.modules.sys.security.SysPrincipal;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysFileService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.entity.AppMsgGroup;
import net.huashitong.Indicators.filter.AppMessageFilter;
import net.huashitong.Indicators.service.AppMessageService;
import net.huashitong.Indicators.service.AppMsgGroupService;
import net.huashitong.Indicators.service.UserInfoService;
import net.huashitong.Indicators.utils.DataTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 我的消息
 */
@Controller
@RequestMapping(value = "web/sendMsg")
public class WebMyInfoController extends JsonBaseController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private AppMessageService appMessageService;
    @Autowired
    private AppMsgGroupService appMsgGroupService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysFileService fileService;

    @Override
    protected String getView(String s) {
        return "modules/appMsg/" + s;
    }

    /**
     * 初始化（发送消息页面）
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        SysPrincipal principal = SysUserUtils.getSysPrincipal();
        String openId = principal.getUserId();
        model.addAttribute("openId", openId);
        return getView("query");
    }

    /**
     * 查询部门树
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryDeptTree", method = RequestMethod.POST)
    public Message queryDeptTree(@RequestBody AppMessageFilter filter) {
        //所有部门
        List<Ztree> trees = sysDeptService.queryDept2Combotree("");
        List<Map<String, Object>> result = appMessageService.getTree(trees);
        List<Map<String, Object>> webResult = new ArrayList<>();

        //查询分组（关联发送方用户）
        List<AppMsgGroup> groups = appMsgGroupService.queryByFilter(filter);
        List<Map<String, Object>> groupList = appMessageService.queryWithMsgGroup2(groups);
        List<Map<String, Object>> partMapList = new ArrayList<>();
        for (Map<String, Object> web2 : groupList) {
            Map<String, Object> webMap2 = new HashMap<>();
            webMap2.put("name", web2.get("name"));
            webMap2.put("last", false);
            Object child2 = web2.get("child");
            List<Map<String, Object>> userMapList = new ArrayList<>();
            if (child2 instanceof ArrayList<?>) {
                for (Object o : (List<?>) child2) {
                    Map<String, Object> userMap = new HashMap<>();
                    String tel = (String) Map.class.cast(o).get("tel");
                    if (StringUtils.isBlank(tel)) {
                        tel = "";
                    } else {
                        tel = "--" + tel;
                    }
                    String name = Map.class.cast(o).get("name") + tel;
                    String value = (String) Map.class.cast(o).get("id");
                    userMap.put("name", name);
                    userMap.put("value", value);
                    userMap.put("last", true);
                    userMap.put("children", new ArrayList<>());
                    userMapList.add(userMap);
                }
            }
            webMap2.put("children", userMapList);
            partMapList.add(webMap2);
        }
        Map<String, Object> groupMap = new HashMap<>();
        groupMap.put("last", false);
        groupMap.put("name", "自定义分组");
        groupMap.put("children", partMapList);
        webResult.add(groupMap);

        for (Map<String, Object> web : result) {
            Map<String, Object> webMap = new HashMap<>();
            webMap.put("name", web.get("name"));
            webMap.put("last", false);
            Object child = web.get("child");
            List<Map<String, Object>> partMapList1 = new ArrayList<>();
            List<Map<String, Object>> partMapListDemo1 = new ArrayList<>();
            if (child instanceof ArrayList<?>) {
                for (Object o : (List<?>) child) {
                    //默认部门map
                    partMapListDemo1.add(Map.class.cast(o));
                }
            }

            for (Map<String, Object> web2 : partMapListDemo1) {
                //最后一级为人员
                if (ObjectUtils.isBlank(web2.get("child"))) {
                    Map<String, Object> userMap = new HashMap<>();
                    String tel = (String) web2.get("tel");
                    if (StringUtils.isBlank(tel)) {
                        tel = "";
                    } else {
                        tel = "--" + tel;
                    }
                    String name = web2.get("name") + tel;
                    String value = (String) web2.get("id");
                    userMap.put("name", name);
                    userMap.put("value", value);
                    userMap.put("last", true);
                    userMap.put("children", new ArrayList<>());
                    partMapList1.add(userMap);
                } else {
                    Map<String, Object> webMap2 = new HashMap<>();
                    webMap2.put("name", web2.get("name"));
                    webMap2.put("last", false);
                    Object child2 = web2.get("child");

                    List<Map<String, Object>> partMapList2 = new ArrayList<>();
                    List<Map<String, Object>> partMapListDemo2 = new ArrayList<>();
                    if (child2 instanceof ArrayList<?>) {
                        for (Object o : (List<?>) child2) {
                            //默认部门map
                            partMapListDemo2.add(Map.class.cast(o));
                        }
                    }
                    for (Map<String, Object> web3 : partMapListDemo2) {
                        //最后一级为人员
                        if (ObjectUtils.isBlank(web3.get("child"))) {
                            Map<String, Object> userMap = new HashMap<>();
                            String tel = (String) web3.get("tel");
                            if (StringUtils.isBlank(tel)) {
                                tel = "";
                            } else {
                                tel = "--" + tel;
                            }
                            String name = web3.get("name") + tel;
                            String value = (String) web3.get("id");
                            userMap.put("name", name);
                            userMap.put("value", value);
                            userMap.put("last", true);
                            userMap.put("children", new ArrayList<>());
                            partMapList2.add(userMap);
                        } else {
                            Map<String, Object> webMap3 = new HashMap<>();
                            webMap3.put("name", web3.get("name"));
                            webMap3.put("last", false);
                            Object child3 = web3.get("child");
                            List<Map<String, Object>> userMapList3 = new ArrayList<>();
                            if (child3 instanceof ArrayList<?>) {
                                List<Map<String, Object>> userMapList4 = new ArrayList<>();
                                for (Object o : (List<?>) child3) {
                                    Map<String, Object> userMap = new HashMap<>();
                                    String tel = (String) Map.class.cast(o).get("tel");
                                    if (StringUtils.isBlank(tel)) {
                                        tel = "";
                                    } else {
                                        tel = "--;" + tel;
                                    }
                                    String name = Map.class.cast(o).get("name") + tel;
                                    String value = (String) Map.class.cast(o).get("id");
                                    userMap.put("name", name);
                                    userMap.put("value", value);
                                    userMap.put("last", true);
                                    userMap.put("children", new ArrayList<>());
                                    userMapList3.add(userMap);
                                }
                            }
                            webMap3.put("children", userMapList3);
                            partMapList2.add(webMap3);
                        }
                    }
                    webMap2.put("children", partMapList2);
                    partMapList1.add(webMap2);
                }
            }
            webMap.put("children", partMapList1);
            webResult.add(webMap);
        }


        return coverMessage("200", "获取成功", webResult);
    }


    /**
     * 新建分组
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createGrouping", method = RequestMethod.POST)
    public Message createGrouping(@RequestBody AppMessageFilter filter) {
        AppMsgGroup group = new AppMsgGroup();
        if (StringUtils.isBlank(filter.getGroupName())) {
            group.setGroupName("新建分组-" + DataTimeUtils.getCurrentDateTime());
        }
        List<String> userIdss = filter.getUserIdss();
        StringBuffer stringBuffer = new StringBuffer();
        for (String str : userIdss) {
            stringBuffer.append(str + ",");
        }
        group.setGroupName(filter.getGroupName());
        group.setUserIds(stringBuffer.toString());
        group.setOpenId(filter.getOpenId());
        appMsgGroupService.save(group);
        return coverMessage("200", "分组创建成功");
    }


//    /**
//     * 发送消息
//     *
//     * @param filter
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "/addAppMsg", method = RequestMethod.POST)
//    public Message addAppMsg(@RequestParam MultipartFile files, AppMessageFilter filter) {
//        String picture = "";
//        if (ObjectUtils.isNotBlank(files)) {
//            try {
//                SysFile sysfile = new SysFile();
//                fileService.saveFile(sysfile, files);
//                picture = sysfile.getUrl();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//        if (ObjectUtils.isBlank(filter.getUserIds())) {
//            return coverMessage("500", "没有填写收件人");
//        }
//        String userIdsStr = filter.getUserIds();
//        String[] users = userIdsStr.split(",");
//        List<String> tmp = new ArrayList<>();
//        for(String str:users){
//            if(str!=null && str.length()!=0){
//                tmp.add(str);
//            }
//        }
//        List<String> userIds = Arrays.asList(users);
//        //发送消息
//        boolean isSuccess = appMessageService.addSendMsg(userIds, filter);
//        if (isSuccess) {
//            return coverMessage("200", "发送成功");
//        } else {
//            return coverMessage("500", "发送失败");
//        }
//    }


    /**
     * 发送消息
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addAppMsg", method = RequestMethod.POST)
    public Message addAppMsg(@RequestBody AppMessageFilter filter) {
        if (ObjectUtils.isBlank(filter.getUserIdss())) {
            return coverMessage("500", "没有填写收件人");
        }
        List<String> userIds = filter.getUserIdss();
        List<String> shortUserIds = filter.getShortUserIdss();
        //发送消息
        boolean isSuccess = appMessageService.addSendMsg(userIds, filter,shortUserIds);
        if (isSuccess) {
            return coverMessage("200", "发送成功");
        } else {
            return coverMessage("500", "发送失败");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/uploadPicture", method = RequestMethod.POST)
    public Message addAppMsg(@RequestParam MultipartFile files) {
        if (ObjectUtils.isNotBlank(files)) {
            try {
                SysFile sysfile = new SysFile();
                fileService.saveFile(sysfile, files);
                String picture = sysfile.getUrl();
                Map map = new HashMap();
                map.put("picture", picture);
                return coverMessage("200", "图片上传成功", map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return coverMessage("200", "没有图片");
    }
}
